﻿using UnityEngine;

public class StoneManager {
	public static StoneManager CreateInstance() {
		var instance = new StoneManager();
		return instance;
	}

	public void Create(GameObject ownerParent) {
		_fieldSize = SettingsLevelModel.FieldSize;
		CreateThisParent(ownerParent);
		CreateStones();
	}

	public void Destroy() {
		Managers.Element.DestroyElements(Tools.Element.GetElements(FieldElementType.Stone));
		Object.Destroy(_parent);
	}

	// === Private ====================================================================================================
	private Vector2 _fieldSize;
	private GameObject _parent;

	private void CreateThisParent(GameObject ownerParent) {
		_parent = new GameObject("Stones");
		_parent.transform.parent = ownerParent.transform;
	}

	private void CreateStones() {
		for (int i = 0; i < SettingsLevelModel.StoneCount; i++) {
			var isCreated = false;
			do {
				var pointX = (int)Random.Range(1, _fieldSize.x - 1);
				var pointY = (int)Random.Range(1, _fieldSize.y - 1);
				var pos = new Vector3(pointX, 0, pointY);
				if (!Tools.Element.HasElement(pos)) {
					CreateElement(pos);
					isCreated = true;
				}
			} while (!isCreated);
		}
	}

	private void CreateElement(Vector3 position) {
		Managers.Element.CreateElement(FieldElementType.Stone, position, _parent);
	}
}